package com.adee.java.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient1 {
    private static ByteBuffer buffer = ByteBuffer.allocate(1024);

    public static void main(String[] args) throws IOException, InterruptedException {
        startClient("Jack");
    }

    public static void sendMsg(String name, SocketChannel sc) throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            ByteBuffer buffer = ByteBuffer.wrap((name + ": " + scanner.nextLine()).getBytes(StandardCharsets.UTF_8));
            sc.write(buffer);
            buffer.clear();
        }
    }

    public static void readMsg(SocketChannel sc) throws IOException {
        Selector selector = Selector.open();
        sc.register(selector, SelectionKey.OP_READ);
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey k = iterator.next();
                iterator.remove();
                SocketChannel rsc = (SocketChannel)k.channel();
                if(k.isReadable()) {
                    buffer.clear();
                    int size = 0;
                    if((size = rsc.read(buffer)) > 0) {
                        buffer.flip();
                        byte[] bytes = new byte[size];
                        buffer.get(bytes);
                        System.out.println(new String(bytes, StandardCharsets.UTF_8));
                    }
                }
            }
        }
    }

    public static void startClient(String name) throws IOException{
        SocketChannel sc = SocketChannel.open(new InetSocketAddress(8000));
        sc.configureBlocking(false);
        // 发送消息
        new Thread(() -> {
            try {
                sendMsg(name, sc);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
        // 读取消息
        new Thread(() -> {
            try {
                readMsg(sc);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}





